<!-- 顶部下拉菜单 -->
<template>
  <div class="dropdown-wrapper" @mouseleave="closeWithDelay">
    <div
      class="dropdown-trigger flex items-center px-1"
      :class="{ hover: isOpen }"
      @mouseenter="openDropdown"
    >
      <slot name="trigger"></slot>
      <el-icon v-if="showArrow" size="12">
        <arrow-down />
      </el-icon>
    </div>
    <transition name="dropdown">
      <div
        class="dropdown-content"
        :style="dropdownStyle"
        v-show="isOpen"
        @mouseenter="cancelClose"
        @mouseleave="closeWithDelay"
      >
        <slot name="content"></slot>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";

const props = defineProps({
  showArrow: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: "left",
  },
  delay: { type: Number, default: 200 },
  width: { type: Number, default: 120 },
});
const isOpen = ref(false);
let closeTimer: any = null;

const dropdownStyle = computed(() => {
  return {
    width: props.width + "px",
    left: props.mode === "left" ? 0 : "auto",
    right: props.mode === "right" ? 0 : "auto",
  };
});


const openDropdown = () => {
  isOpen.value = true;
  cancelClose();
};

const closeWithDelay = () => {
  closeTimer = setTimeout(() => {
    isOpen.value = false;
  }, props.delay);
};

const onMouseLeave = () => {
  isOpen.value = false;
};

const cancelClose = () => {
  if (closeTimer) {
    clearTimeout(closeTimer);
    closeTimer = null;
  }
};
</script>

<style scoped lang="scss">
.dropdown-wrapper {
  position: relative;
  display: inline-block;
  height: 35px;
  .dropdown-trigger {
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
    height: 100%;
    border-left: 1px solid #ffffff;
    border-right: 1px solid #ffffff;
    z-index: 210;
    position: relative;
  }

  .dropdown-content {
    position: absolute;
    top: 100%;
    left: 0;
    min-width: 120px;
    background: white;
    border: 1px solid #eee;
    border-radius: 0 0 4px 4px;
    transform: translateY(-1px);
    z-index: 205;
  }
  .hover {
    background: #fff;
    border-left: 1px solid #eee;
    border-right: 1px solid #eee;
  }
}
/* 过渡动画 */
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.3s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
